#!/bin/env python3
# -*- encoding=utf8 -*-
#******************************************************************************
# Copyright (c) Huawei Technologies Co., Ltd. 2020-2020. All rights reserved.
# licensed under the Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#     http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
# PURPOSE.
# See the Mulan PSL v2 for more details.
# Author: wangchong
# Create: 2021-07-09
# ******************************************************************************

"""
copy project packages
"""
import os
import sys
from concurrent.futures import ThreadPoolExecutor
from log_obs import log

class obs(object):
    def __init__(self, **kwargs):
        self.kwargs = kwargs
        self.src_proj = self.kwargs["src_proj"]
        self.dest_proj = self.kwargs["dest_proj"]
        self.pkglistfile = self.kwargs["pkglistfile"]

    def build(self, pkg):
        """
        copy a package
        """
        cmd = "osc copypac %s %s %s" % (self.src_proj, pkg, self.dest_proj)
        ret = os.popen(cmd).read()
        print("ret", ret)
        if "HTTP Error 404" in ret:
            log.error("Failed osc copy %s %s to %s." % (self.src_proj, pkg, self.dest_proj))
        else:
            log.info("Succeed osc copy %s %s to %s." % (self.src_proj, pkg, self.dest_proj))

    def build_all_packages(self):
        file_msg = []
        if os.path.exists(self.pkglistfile):
            data = open(self.pkglistfile, "r")
            for line in data:
                file_msg.append(line.strip('\n'))
            data.close()
        else:
            print("[ERROR]: %s is not exits." % self.pkglistfile)
            return -1
        with ThreadPoolExecutor(50) as job:
            for pkg in file_msg:
                job.submit(self.build, pkg)

if __name__ == "__main__":
    if len(sys.argv) == 4:
        kw = {"src_proj": sys.argv[1], "dest_proj": sys.argv[2], "pkglistfile":sys.argv[3]}
        obs = obs(**kw)
        obs.build_all_packages()
    else:
        print("Please check parameter, you should run as: python3 %s [src_projectname] [dest_projectname] [pkglistfile]" % sys.argv[0])
